<template>
    <div class="table">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <!-- <el-breadcrumb-item><i class="el-icon-lx-cascades"></i> 订单表格</el-breadcrumb-item> -->
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button type="primary" icon="el-icon-plus" class="mr10" @click="add" v-if="tableData.length == 0">添加</el-button>
                <!-- <el-button type="primary" icon="delete" class="handle-del mr10" @click="delAll">批量删除</el-button> -->
                <!-- <el-select v-model="select_cate" placeholder="筛选省份" class="handle-select mr10">
                    <el-option key="1" label="广东省" value="广东省"></el-option>
                    <el-option key="2" label="湖南省" value="湖南省"></el-option>
                </el-select> -->
               <!--  <el-input v-model="select_word" placeholder="筛选关键词" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="search" @click="search">搜索</el-button> -->
            </div>
            <el-table :data="tableData" border class="table" ref="multipleTable" @selection-change="handleSelectionChange">
                <!-- <el-table-column type="selection" width="55" align="center"></el-table-column> -->
                
                <el-table-column prop="id" label="ID" align="center">
                </el-table-column>
                <el-table-column prop="title" label="标题" sortable align="center" show-overflow-tooltip>
                </el-table-column>

                <el-table-column prop="img" label="图片" sortable align="center">
                   <template slot-scope="scope">
                         <a :href="scope.row.img"><img :src="scope.row.img" style="width: 50px;height: 50px;"></a>
                    </template>
                </el-table-column>
                 <el-table-column prop="detail" label="内容" sortable align="center">
                  <template slot-scope="scope">
                        <el-button size="mini" prop="scope.row.detail" type="primary" plain @click="ShowDetail(scope.$index, scope.row)">显示</el-button>
                    </template>
                </el-table-column>
                 <el-table-column prop="banner" label="banner" sortable align="center">
                     <template slot-scope="scope">
                        <el-button size="mini" prop="scope.row.detail" type="primary" plain @click="ShowBanner(scope.$index, scope.row)">显示</el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="update_time" label="更新时间" sortable align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column fixed='right' label="操作" align="center" width='150'>
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <!-- <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index, scope.row)">删除</el-button> -->
                    </template>
                </el-table-column>
            </el-table>
          <!--   <div class="pagination">
                <el-pagination background @current-change="handleCurrentChange" layout="prev, pager, next" :total="total">
                </el-pagination>
            </div> -->
        </div>

        <el-dialog title="商品详情" :visible.sync="dialogShow">
            <!--<template>
                <el-table :data="tableData" border style="width: 100%" ref="multipleTable">
                    <el-table-column prop="good_content" label="商品详情"></el-table-column>
                </el-table>
            </template>-->
            <div id="editor-html" v-html="msg" style="/*max-width: 100%;*/overflow: hidden;"></div>
            <!--  <quill-editor v-model="msg" ref="myQuillEditor2" :options="editorOption2" @ready="onEditorReady($event)">
                    </quill-editor> -->
            </el-dialog>

        <el-dialog title="banner详情" :visible.sync="bannerShow" width="50%">
            <!--<template>
                <el-table :data="tableData" border style="width: 100%" ref="multipleTable">
                    <el-table-column prop="good_content" label="商品详情"></el-table-column>
                </el-table>
            </template>-->
         <el-table :data="gridData">
            <el-table-column property="id" label="banner_id"></el-table-column>
            <el-table-column property="img" label="图片" >
                 <template slot-scope="scope">
                         <a :href="scope.row.img"><img :src="scope.row.img" style="width: 50px;height: 50px;"></a>
                    </template>
            </el-table-column>
            <el-table-column property="space_id" label="空间ID"></el-table-column>
            <el-table-column property="update_time" label="更新时间"></el-table-column>
          </el-table>
            <!--  <quill-editor v-model="msg" ref="myQuillEditor2" :options="editorOption2" @ready="onEditorReady($event)">
                    </quill-editor> -->


            </el-dialog>
        <!-- 编辑弹出框 -->
        <el-dialog :title="title" :visible.sync="editVisible" width="70%">
            <el-form ref="form" :label-position="labelPosition" :model="form" label-width="100px">
                <el-form-item label="标题">
                    <el-input v-model="form.title"></el-input>
                </el-form-item>
                <!--  <el-form-item label="描述">
                    <el-input type="textarea" v-model="form.detail" placeholder="请输入内容"></el-input>
                </el-form-item> -->
                 <el-form-item label="图文">
                    <!-- <el-input v-model="form.content"></el-input> -->
                    <el-upload class="avatar-uploader" :action="'https://qkj.zjinyi.cn/admin/upload/img'" name="img" :headers="header" :show-file-list="false" :on-success="uploadSuccess" :on-error="uploadError" :before-upload="beforeUpload"></el-upload>
        <!--富文本编辑器组件-->
                   <el-row v-loading="uillUpdateImg">
                    <quill-editor v-model="form.detail" ref="myQuillEditor" :options="editorOption" @change="onEditorChange($event)" @ready="onEditorReady($event)">
                    </quill-editor>
                   </el-row>
                </el-form-item>
                 <el-form-item label="主图">
                    <!-- <el-input v-model="form.img"></el-input>  -->
                    <el-upload class="upload-demo" :action="'https://qkj.zjinyi.cn/admin/upload/img'" :on-success="handleUploadSuccess" :on-remove="handleRemoveMain" name="img" :headers="token" multiple :limit="1" :file-list="imgList" list-type="picture">
                        <el-button size="small" type="primary">上传主图</el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 删除提示框 -->
        <el-dialog title="提示" :visible.sync="delVisible" width="300px" center>
            <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="delVisible = false">取 消</el-button>
                <el-button type="primary" @click="deleteRow">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 上下架 提示框 -->
        <el-dialog title="提示" :visible.sync="rackVisible" width="300px" center>
            <div class="del-dialog-cnt">是否确定上下架该分类？</div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="reckQuit">取 消</el-button>
                <el-button type="primary" @click="reckRow">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import { quillEditor } from 'vue-quill-editor';

    const toolbarOptions = [
                  ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
                  ['blockquote', 'code-block'],

                  [{'header': 1}, {'header': 2}],               // custom button values
                  [{'list': 'ordered'}, {'list': 'bullet'}],
                  [{'script': 'sub'}, {'script': 'super'}],      // superscript/subscript
                  [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
                  [{'direction': 'rtl'}],                         // text direction

                  [{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
                  [{'header': [1, 2, 3, 4, 5, 6, false]}],

                  [{'color': []}, {'background': []}],          // dropdown with defaults from theme
                  [{'font': []}],
                  [{'align': []}],
                  ['image'],
                  ['clean']                                         // remove formatting button
        ]
    export default {
        inject : ['reload'],
        name: 'basetable',
        data() {
            return {
                labelPosition:"left",
                /*富文本配置*/

                quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画，刚开始是false,不显示
                //serverUrl: API_PATH + '/good_store/uploadDetail',  
                // 这里写你要上传的图片服务器地址
                header: {
                    //token: localStorage.getItem('admin-token')
                },  // 有的图片服务器要求请求头需要有token之类的参数，写在这里
                detailContent: '', // 富文本内容

                editorOption: {
                    // placeholder: 'Hello World'
                    // editorOption: {
                        placeholder: '',
                        theme: 'snow',  // or 'bubble'
                        modules: {
                            toolbar: {
                                container: toolbarOptions,  // 工具栏
                                handlers: {
                                    'image': function (value) {
                                        if (value) {
                                            // document.querySelector('#quill-upload input').click()
                                            // alert(1)
                                             document.querySelector('.avatar-uploader input').click()
                                        } else {
                                            this.quill.format('image', false);
                                        }
                                    }
                                }
                            }
                        }
                    // }
                },
                imgList:[],
                // url: './static/vuetable.json',
                gridData:[],
                tableData: [],
                cur_page: 1,
                multipleSelection: [],
                select_cate: '',
                select_word: '',
                del_list: [],
                is_search: false,
                editVisible: false,
                delVisible: false,
                dialogShow:false,
                bannerShow:false,
                form: {
                    update_time: '',
                    type_id:'',
                    type_name:'',

                },
                idx: -1,
                admininfo:JSON.parse(localStorage.getItem('ms_username')),
                total:1,
                title:'',
                rackVisible:false,
            }
        },
        created() {
            this.getData();
        },
        computed: {
            data() {
                return this.tableData.filter((d) => {
                    let is_del = false;
                    for (let i = 0; i < this.del_list.length; i++) {
                        if (d.id === this.del_list[i].id) {
                            is_del = true;
                            break;
                        }
                    }
                    if (!is_del) {
                        if(d.id.indexOf(this.select_word) > -1 ) {
                            return d;
                        }
                    }
                })
            }
        },
        methods: {
            beforeUpload(file) {
                 this.quillUpdateImg = true
                 const suffix = file.name.split('.')
                 const ext = suffix.splice(suffix.length - 1, 1)[0]
                 console.log(suffix)
            },
            // 上传图片成功
            uploadSuccess(res, file) {
                // res为图片服务器返回的数据
                // 获取富文本组件实例
                let quill = this.$refs.myQuillEditor.quill
                // 如果上传成功
                if (res.code == 0) {
                    // 获取光标所在位置
                    let length = quill.getSelection().index;
                    // 插入图片  res.info为服务器返回的图片地址
                    quill.insertEmbed(length, 'image', res.data.url)
                    // 调整光标到最后
                    quill.setSelection(length + 1)
                } else {
                    this.$message.error('图片插入失败')
                }
                // loading动画消失
                this.quillUpdateImg = false
            },
            // 上传图片失败
            uploadError(res, file) {
                // loading动画消失
                this.quillUpdateImg = false
                this.$message.error('图片插入失败')
            },

            ShowDetail(index,row){
                // console.log(row.good_content)
                this.dialogShow = true
                this.msg = row.detail
//              this.html = 
//               template: `<div v-html= "this.tableData.good_content" ></div>`
//              msg:"<h2>"+row.good_content+"</h2>"
            },
            ShowBanner(index ,row){
                this.bannerShow = true
                this.gridData = row.banner
            },

            handleUploadSuccess(res,file){
                if(res.code == 0) {
                    this.$message.success('上传成功')
                    this.form.img = res.data.url 
                } else {
                    this.$message.error(res.msg)
                }
            },
            handleRemoveMain(){

            },

            // 分页导航
            handleCurrentChange(val) {
                this.cur_page = val;
                this.getData();
            },
            // 获取 easy-mock 的模拟数据
            getData() {
                // 开发环境使用 easy-mock 数据，正式环境使用 json 文件
                // if (process.env.NODE_ENV === 'development') {
                //     this.url = '/ms/table/list';
                // };
                // this.$axios.get(this.url, {
                //     page: this.cur_page
                // }).then((res) => {
                //     this.tableData = res.data.list;
                // })
                // console.log(this.admininfo)
                  this.$axios.get('/admin/space/list', {
                    params:{
                        aid: this.admininfo['admin_id'],
                        token: this.admininfo['token'],
                        page: this.cur_page
                    }
                }).then((res) => {
                    console.log(res)
                    if(res.data.code == 0){
                            this.tableData = res.data.data;
                            // this.total = res.data.total 
                        }else if(res.data.code == 3){
                           this.$router.push('login') 
                        }
                })

            },
            search() {
                this.is_search = true;
            },
            formatter(row, column) {
                return row.address;
            },
            filterTag(value, row) {
                return row.tag === value;
            },
            add(){
                this.title = '添加'
                this.form = {
                      title: '',
                      detail: '',
                      // content: '',
                      img:'',
                  }
                this.editVisible = true 

              },
              handleEdit(index ,row) {
                  this.title = '编辑'
                  this.idx = index;
                  const item = this.tableData[index];
                  this.form = {
                      id: item.id,
                      title: item.title,
                      detail: item.detail,
                      // content: item. content,
                      img:item.img,
                  }
                  this.imgList = [{
                        name: 'img',
                        url: row.img
                    }]
                this.editVisible = true;

            },
            handleDelete(index, row) {
                this.idx = index;
                this.delVisible = true;
            },
            delAll() {
                const length = this.multipleSelection.length;
                let str = '';
                this.del_list = this.del_list.concat(this.multipleSelection);
                for (let i = 0; i < length; i++) {
                    str += this.multipleSelection[i].name + ' ';
                }
                this.$message.error('删除了' + str);
                this.multipleSelection = [];
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            // 保存编辑
            saveEdit() {
                     const obj =  {
                        aid: this.admininfo.admin_id,
                        token: this.admininfo.token
                    };
                    const data = Object.assign(obj,this.form);
                 if(this.title == '添加'){
                    // let date = new Date()
                    // this.form.update_time = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds()
                    // this.tableData.push(this.form)
                    // // this.$set(this.tableData, this.idx, this.form);
                    // this.total = this.tableData.length+1
                    // this.editVisible = false;

                     this.$axios.post('/admin/space/add',data).then((res) =>{
                        console.log(res.code);
                        if(res.data.code == 0){
                            this.$message.success(`添加成功`);
                            this.reload()
                        }else{
                            this.$message.error(res.data.msg);
                        }
                    }) 
                    

                }else if(this.title == '编辑'){
                    // this.$set(this.tableData, this.idx, this.form);
                    // this.editVisible = false;
                    // this.$message.success(`修改第 ${this.idx+1} 行成功`);
                     this.$axios.post('/admin/space/edit',data).then((res) =>{
                        if(res.data.code == 0){
                            this.$message.success(`修改成功`);
                            this.reload()
                        }else{
                            this.$message(res.data.msg);
                        }
                    })
                }
            },
            // 确定删除
            deleteRow(){

                // this.tableData.splice(this.idx, 1);
                // this.$message.success('删除成功');
                // this.delVisible = false;
                this.$axios.delete('/admin/news/delete',{params:{
                        aid: this.admininfo.admin_id,
                        token: this.admininfo.token,
                        id:  this.tableData[this.idx].id
                }}).then((res) =>{
                        if(res.data.code == 0){
                            this.$message.success(`删除成功`);
                            this.reload()
                        }else if(res.data.code == 30){
                            this.delVisible=false
                             this.$message.error(`${res.data.msg},还存在该分类商品`);


                        }else{
                            this.$message(res.data.msg);
                        }
                    })
            },
             rack(index,row){
                this.idx = index;
                this.rackVisible = true;
              },
            reckRow(){
                this.rackVisible = false;
                this.$axios.post('admin/type/set_rack',{
                        aid:this.admininfo.admin_id,
                        token:this.admininfo.token,
                        type_id:this.tableData[this.idx].type_id
                    }).then((res)=>{
                        if(res.data.code == 0){
                            this.$message.success('修改成功');
                            // this.reload()
                        }else{
                             this.$message(res.data.msg);
                        }
                    })

              },
              reckQuit(){
                this.rackVisible = false
                this.tableData[this.idx].rack = false
              }
            
        }
    }

</script>

<style scoped>
/*.container{
    max-width: 900px;
}*/
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }
    .del-dialog-cnt{
        font-size: 16px;
        text-align: center
    }
    .table{
        width: 100%;
        font-size: 14px;
    }
    .red{
        color: #ff0000;
    }

</style>
<style type="text/css">
    .el-upload--text {
        border: none !important;
        text-align: left;
        margin-left: 10px;
        height: 50px;
    }
</style>
